<template>
    <div>
        <el-container class="search-container">
        <el-header class="search">
            <!-- native，用到原生js的方法时，需要加native才会生效 -->
            <el-input  placeholder="请输入歌曲、歌手、专辑" v-model="queryinfo.keywords" class="input" @keyup.enter.native="getMusicList" clearable>
             <el-button slot="append" icon="el-icon-search" @click="getMusicList">搜索</el-button>
         </el-input>
        </el-header>

        <el-main style="width: 100%" >
            <div v-if="loading" class="loading" v-loading="loading" ></div>
                <el-table
                class="musicTable"
                :data="musiclist"
                style="width: 100%"
                stripe
                fit
                v-if="!loading">
                <el-table-column
                    type="index" label="#" >
                </el-table-column>
                <el-table-column

                    label="歌曲名称"
                    min-width="35%">
                    <template v-slot='scope'>
                        <i v-if="play&&activeIndex===scope.$index" class="el-icon-video-pause" style="cursor: pointer;margin-right:3px" @click="broadcastMusic(scope.$index,scope.row,btnSt='stop')"> {{scope.row.title}}</i>
                        <i v-else class="el-icon-video-play" style="cursor: pointer;margin-right:3px" @click="broadcastMusic(scope.$index,scope.row,btnSt='broadcast')"> {{scope.row.title}} </i>
                        <el-tag type="danger" size="mini" class="viptag" v-if="!scope.row.src">会员</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="artist"
                    label="歌手"
                    min-width="20%">
                </el-table-column>
                <el-table-column
                    prop="albumname"
                    label="专辑"
                    min-width="25%">
                </el-table-column>
                <el-table-column
                    label="时长"
                    min-width="15%">
                    <template v-slot="scope">
                    {{scope.row.dt | dtFormat}}
                </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    min-width="20%">
                    <template v-slot="scope">
                        <el-tooltip effect="light" content="下载" placement="top">
                            <el-button icon="el-icon-download" circle size="mini" @click="downloadSong(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip  effect="light" content="复制链接" placement="top">
                            <el-button  class="copy_url" icon="el-icon-document-copy" circle size="mini" @click="copySongUrl(scope.row)"></el-button>
                        </el-tooltip>

                </template>
                </el-table-column>
            </el-table>

        </el-main>
        </el-container>
        <div  id="music-player">
            <!-- 折叠面板，暂不做 -->
            <!-- <el-button @click="show3 = !show3">Click Me</el-button>
           <div style="margin-top: 20px; height: 200px;">
      <el-collapse-transition>
        <div v-show="show3">
          <div class="transition-box">el-collapse-transition</div>
          <div class="transition-box">el-collapse-transition</div>
        </div>
      </el-collapse-transition>
           </div> -->
            <!-- listFolded歌曲列表折叠、listMaxHeight最大高度 -->
           <aplayer
           fixed
           :lrcType="1"
           :showLrc="true"
           @pause="pauseEvent"
           @playing="playEvent"
           @error="errorEvent"
           v-if="aplayerVisible"
           ref="aplayer"
           :listFolded  ='true'
           listMaxHeight ="100px"
            :music="music"
            :list="musiclist"
            />
        </div>

    </div>
</template>

<script>

// 引入复制组件
import Clipboard from 'clipboard'
// 引入下载文件组件
var Filesaver = require('file-saver')
export default {
  data () {
    return {
      queryinfo: {
        keywords: '星辰大海'
      },
      music: {},
      musiclist: [],
      //   歌曲id
      //   songId: '',
      //   songUrl: '',
      //   控制播放按钮图标
      activeIndex: 0,
      play: false,
      //   歌曲列表 播放器图片标题、作者、音乐链接、图片url
      //   取musiclist
      //   audiolist: [
      //     {
      //       title: '海阔天空',
      //       artist: 'beyond',
      //       src: 'http://m7.music.126.net/20210907183400/f80aba49ebc0e8059bafb5ab83bf485c/ymusic/76e5/ba34/d562/2e95d6640354faee9ef0d6a384d2bc5f.mp3',
      //       pic: 'http://p4.music.126.net/zZtUDuWk6qIe3ezMt4UMjg==/109951165796417308.jpg'
      //     }
      //   ],
      //   控制播放器显示
      aplayerVisible: false,
      // 控制播放面板的展示与隐藏
      show3: true,
      loading: false
    }
  },
  created () {

  },
  methods: {

    getMusicList () {
      // 搜索时隐藏播放器组件
      this.aplayerVisible = false
      //   显示loading
      this.loading = true
      // 请求 cloudsearch 搜索接口
      this.$http.get('cloudsearch', { params: this.queryinfo }).then(({ data: res }) => {
        if (res.code !== 200) return this.$message.error('获取音乐搜索结果失败')

        this.musiclist = res.result.songs
        // console.log('this.musiclist:', this.musiclist)
        // 使用for循环将 artists 中的值转换为 artists.name
        this.musiclist.forEach(async item => {
        //   console.log('item:', item)
        // 歌曲名称
          item.title = item ? item.name : []
          // 歌曲作者
          item.artist = item.ar ? item.ar[0].name : []
          //   专辑名称
          item.albumname = item.al ? item.al.name : []
          //   歌曲封面
          item.pic = item.al ? item.al.picUrl : []
          //   获取歌曲id
          const songId = item.id
          //   歌曲url
          const songUrl = await this.getSongUrl(songId)
          //   console.log('songUrl:', songUrl)
          item.src = songUrl
          //   获取歌词
          const songLrc = await this.getSongLrc(songId)
          item.lrc = songLrc
          //   判断歌曲是否 是vip
        //   const canplay = await this.checkSong(songId)
        //   item.canplay = canplay
        })

        console.log('this.musiclist:', this.musiclist)
        // 加上1s延时，解决for循环还没结束就渲染表格导致表格数据显示不全的问题
        setTimeout(() => {
          this.loading = false
        }, 1500)
      }).catch(e => {
        this.$message.error('获取音乐搜索结果失败')
        this.loading = false
      })
    },
    // 获取歌曲链接
    async getSongUrl (songId) {
      const { data: res } = await this.$http.get('song/url', { params: { id: songId } })
      if (res.code !== 200) return this.$message.error('获取音乐链接失败')
      this.songUrl = res.data[0].url
      //   console.log('this.songUrl:', this.songUrl)
      return this.songUrl
    },
    // 判断歌曲是否可用
    async checkSong (songId) {
      try {
        //   如果是会员则success返回true
        const { data: res } = await this.$http.get('check/music', { params: { id: songId } })
        console.log('checkSong', res)
        return res.success
      } catch (err) {
        var res = err.response.data
        // 否则返回false
        console.log('checkSong catch', res)
        return res.success
      }
    },
    // 通过 id 获取歌词
    async getSongLrc (songId) {
      const { data: res } = await this.$http.get('lyric', { params: { id: songId } })
      if (res.code !== 200) return this.$message.error('获取音乐歌词失败')
      try {
        var songLrc = res.lrc.lyric
        // console.log('songLrc:', songId, songLrc)
        // 如果歌词格式不对，不显示歌词
        if (songLrc.indexOf('[0') === -1) return '[00:00.000] (,,•́ . •̀,,) 抱歉，当前歌曲暂无歌词'
      } catch {
        // console.log('songLrc:', songId, songLrc)
        // 没有歌词时,显示 暂无歌词
        return '[00:00.000] (,,•́ . •̀,,) 抱歉，当前歌曲暂无歌词'
      }
      return songLrc
    },
    // 通过nextTick方法，使播放器组件渲染完成后再执行play方法，防止报错,该play方法从vue-aplayer.vue方法中获得
    thenPlay () {
      this.$nextTick(() => {
        console.log('this.$refs.aplayer:', this.$refs.aplayer)
        this.$refs.aplayer.play()
      })
    },
    // 播放歌曲
    broadcastMusic (index, scopeRow, btnSt) {
    //   console.log(index, this.activeIndex)
    // 判断歌曲能不能播放
      console.log(index, scopeRow.canplay)
      if (!scopeRow.src) return this.$message.error('这歌需要会员，你听不了')
      // 控制播放/暂停icon的显示
      if (btnSt === 'broadcast') {
        this.activeIndex = index
        this.play = true
      } else {
        this.play = false
      }
      // 显示播放器组件
      this.aplayerVisible = true
      //   console.log('this.row:', scopeRow)
      //   try catch 判断是否有currentMusic属性，并捕获异常
      try {
        //   判断是否有currentMusic属性，如果有执行暂停或播放选中的另外一首
        if (this.$refs.aplayer.currentMusic === scopeRow) {
          this.$refs.aplayer.toggle()
        } else {
          // 将当前currentMusic属性赋予新的song对象
          this.$refs.aplayer.currentMusic = scopeRow
          this.thenPlay()
        }
      } catch {
        //   如果没有currentMusic属性，执行播放方法
        this.music = scopeRow
        this.thenPlay()
      }
    },

    // 下载歌曲
    async downloadSong (scopeRow) {
    //   console.log(scopeRow)
      if (!scopeRow.src) return this.$message.error('这歌需要会员，你下不了')
      const songUrl = scopeRow.src
      const songName = scopeRow.title
      this.$notify({
        title: '下载',
        dangerouslyUseHTMLString: true,
        message: '<div>正在下载 <strong>' + songName + '</strong> ，请稍等...</div> ',
        type: 'success',
        duration: 2500
      })
      await Filesaver.saveAs(songUrl, songName + '.mp3')
    },
    // 复制歌曲链接
    async copySongUrl (scopeRow) {
      if (!scopeRow.src) return this.$message.error('这歌需要会员，你复制不了')
      const songUrl = 'https://music.163.com/song/media/outer/url?id=' + scopeRow.id + '.mp3 '
      //   console.log('触发了copySongUrl', songUrl)
      const clipboard = new Clipboard('.copy_url', {
        text: function () {
          return songUrl
        }
      })
      clipboard.on('success', e => {
        // console.log(e.text)
        this.$message.success(' 已复制到剪贴板！')
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        e.clearSelection()
        clipboard.destroy()
      })
    },
    // 监听播放器暂停事件，暂停时将play置为false，使得；列表中的icon变为播放icon
    pauseEvent (e) {
      console.log('pauseEvent:', e)
      var index = this.musiclist.indexOf(this.$refs.aplayer.currentMusic)
      //   console.log('index:', index)
      this.activeIndex = index
      this.play = false
    },
    // 监听播放器播放事件，播放时将play置为true，使得；列表中的icon变为暂停icon
    playEvent (e) {
      console.log('playEvent:', e)
      var index = this.musiclist.indexOf(this.$refs.aplayer.currentMusic)
      //   console.log('index:', index)
      this.activeIndex = index
      this.play = true
    },
    // 监听播放报错，失败时提示
    errorEvent (e) {
    //   console.log('errorEvent:', e)
      this.play = false
      this.$message.error('播放失败，请刷新页面重试')
    }
  }
}
</script>

<style  scoped>
.search-container{
    width: 95%;
    margin: 0 auto;
}
.search{
    margin-top: 30px;
}
.input{
    width: 50%;
}
 /* 监听屏幕的宽度，当宽度小于500px时，元素属性改变 */
    @media screen and (max-width:500px){
        .input{
                width: 80%;
            }
        .el-main{
            padding: 20px 0px;
        }
        }

.el-header{
    text-align: center;
}
.el-input-group>.el-input__inner{
    border: 2px solid #ccd0d7
}
.el-main{
    margin: 0 auto;
    margin-bottom: 145px;
}
/* 设定高度，防止出现滚动条 */
.loading{
    height: 100px;
}
.el-table__row--striped{
    background: #f1f2f6;
}

/* 播放器 固定在屏幕底部*/
#music-player{
    position: fixed;
    bottom: 0;
    width: 100%;
    /* height: 500; */
    left: 0;
}

/* .transition-box {
    margin-bottom: 10px;
    width: 200px;
    height: 100px;
    border-radius: 4px;
    background-color: #409EFF;
    text-align: center;
    color: #fff;
    padding: 40px 20px;
    box-sizing: border-box;
    margin-right: 20px;
  } */

</style>
